//
//  LiveShowViewController.m
//  LiveVideoCoreDemo
//
//  Created by Alex.Shi on 16/3/2.
//  Copyright © 2016年 com.Alex. All rights reserved.
//

#import "LiveShowViewController.h"
#import "FFMediaPlayer+vp.h"
#import "LiveVideoCoreSDK.h"

@interface LiveShowViewController() <FFMediaPlayerDelegate, LIVESessionDelegate, UIGestureRecognizerDelegate> {
    UIView  *_cameraPreview;
    UIView  *_playerBackgroundView1;
    UIView  *_playerBackgroundView2;
    FFMediaPlayer* _player1;
    FFMediaPlayer* _player2;
    NSString *_rtmpUrl;
    NSString *_playUrl;
    UIButton* _startButton;
    UIButton* _ExitButton;
    UILabel*  _RtmpStatusLabel;
    UILabel*  _bitrateLabel;
    UIButton* _CameraChangeButton;
    BOOL _bCameraFrontFlag;
    UIButton* _FilterButton;
    BOOL _bBeautyFilterOnFlag;
    UIButton* _flashButton;
    BOOL _bTorchOnFlag;

    int _uid;
    UIView *_pinchView;
    UIPinchGestureRecognizer *_pinchGestureRecognizer;
    UITapGestureRecognizer   *_tapGestureRecognizer;
    CGFloat _lastScale;
    
    float _screenWidth;
    float _screenHeight;
}

@end

@implementation LiveShowViewController

- (void)UIInit
{
    _screenWidth = [UIScreen mainScreen].bounds.size.width;
    _screenHeight = [UIScreen mainScreen].bounds.size.height;
    
    /* 摄像头预览视图 */
    _cameraPreview = [[UIView alloc] initWithFrame:CGRectMake(0, 0, _screenWidth, _screenHeight)];
    [self.view addSubview: _cameraPreview];
    
    /* 手势控制视图 */
    _pinchView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, _screenWidth, _screenHeight)];
    _pinchView.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0];
    [self.view addSubview:_pinchView];
    _pinchGestureRecognizer = [[UIPinchGestureRecognizer alloc]
                               initWithTarget:self
                               action:@selector(handlePinch:)];
    _pinchGestureRecognizer.delegate = self;
    [_pinchView addGestureRecognizer:_pinchGestureRecognizer];
    _tapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTapGestureRecognizer:)];
    [_pinchView addGestureRecognizer:_tapGestureRecognizer];
    
    /* 关闭按钮 */
    CGFloat fExitButtonW = 40;
    CGFloat fExitButtonH = 40;
    CGFloat fExitButtonX = _screenWidth - fExitButtonW;
    CGFloat fExitButtonY = 30;
    _ExitButton = [[UIButton alloc] initWithFrame:CGRectMake(fExitButtonX, fExitButtonY, fExitButtonW, fExitButtonH)];
    [_ExitButton setImage:[UIImage imageNamed:@"ic_live_close_normal"] forState:UIControlStateNormal];
    _ExitButton.layer.masksToBounds = YES;
    _ExitButton.layer.cornerRadius  = 5;
    [_ExitButton addTarget:self action:@selector(OnExitBtnClicked:) forControlEvents:UIControlEventTouchDown];
    [self.view addSubview:_ExitButton];
    
    /* 美颜开关按钮 */
    CGFloat fFilterButtonW = 40;
    CGFloat fFilterButtonH = 40;
    CGFloat fFilterButtonX = _screenWidth - fFilterButtonW;
    CGFloat fFilterButtonY = _screenHeight - 45;
    
    _FilterButton = [[UIButton alloc] initWithFrame:CGRectMake(fFilterButtonX, fFilterButtonY, fFilterButtonW, fFilterButtonH)];
    [_FilterButton setImage:[UIImage imageNamed:@"ic_live_beauty_open"] forState:UIControlStateNormal];
    _FilterButton.layer.masksToBounds = YES;
    _FilterButton.layer.cornerRadius  = 5;
    [_FilterButton addTarget:self action:@selector(OnFilterBtnClicked:) forControlEvents:UIControlEventTouchDown];
    [self.view addSubview:_FilterButton];
    
    /* 切换摄像头按钮 */
    CGFloat fCameraChangeButtonX = fFilterButtonX - 45;
    CGFloat fCameraChangeButtonY = _screenHeight - 45;
    CGFloat fCameraChangeButtonW = 40;
    CGFloat fCameraChangeButtonH = 40;
    _CameraChangeButton = [[UIButton alloc] initWithFrame:CGRectMake(fCameraChangeButtonX, fCameraChangeButtonY, fCameraChangeButtonW, fCameraChangeButtonH)];
    _CameraChangeButton.layer.masksToBounds = YES;
    _CameraChangeButton.layer.cornerRadius  = 5;
    [_CameraChangeButton setImage:[UIImage imageNamed:@"ic_live_camera_switch"] forState:UIControlStateNormal];
    [_CameraChangeButton addTarget:self action:@selector(OnCameraChangeBtnClicked:) forControlEvents:UIControlEventTouchDown];
    [self.view addSubview:_CameraChangeButton];
    
    /* 闪光灯开关按钮 */
    CGFloat fFlashButtonX = fCameraChangeButtonX - 45;
    CGFloat fFlashButtonY = _screenHeight - 45;
    CGFloat fFlashButtonW = 40;
    CGFloat fFlashButtonH = 40;
    _flashButton = [[UIButton alloc] initWithFrame:CGRectMake(fFlashButtonX, fFlashButtonY, fFlashButtonW, fFlashButtonH)];
    _flashButton.backgroundColor = [UIColor colorWithRed:247.0/255.0 green:247.0/255.0 blue:247.0/255.0 alpha:1.0];
    _flashButton.layer.masksToBounds = YES;
    _flashButton.layer.cornerRadius  = 22;
    [_flashButton setImage:[UIImage imageNamed:@"ic_camera_flash_close"] forState:UIControlStateNormal];
    [_flashButton addTarget:self action:@selector(onFlashBtnClicked:) forControlEvents:UIControlEventTouchDown];
    [self.view addSubview:_flashButton];
    
    /* 推流状态显示 */
    float fRtmpStatusLabelW = 200;
    float fRtmpStatusLabelH = 20;
    float fRtmpStatusLabelX = 10;
    float fRtmpStatusLabelY = 30;
    _RtmpStatusLabel = [[UILabel alloc] initWithFrame:CGRectMake(fRtmpStatusLabelX, fRtmpStatusLabelY, fRtmpStatusLabelW, fRtmpStatusLabelH)];
    _RtmpStatusLabel.backgroundColor = [UIColor lightGrayColor];
    _RtmpStatusLabel.layer.masksToBounds = YES;
    _RtmpStatusLabel.layer.cornerRadius  = 5;
    _RtmpStatusLabel.font = [UIFont fontWithName:@"Helvetica-Bold" size:14];
    [_RtmpStatusLabel setTextColor:[UIColor whiteColor]];
    _RtmpStatusLabel.text = @"RTMP状态: 未连接";
    [self.view addSubview:_RtmpStatusLabel];
    
    /* 码率显示 */
    float fBitrateLabelW = 200;
    float fBitrateLabelH = 20;
    float fBitrateLabelX = 10;
    float fBitrateLabelY = 60;
    _bitrateLabel = [[UILabel alloc] initWithFrame:CGRectMake(fBitrateLabelX, fBitrateLabelY, fBitrateLabelW, fBitrateLabelH)];
    _bitrateLabel.backgroundColor = [UIColor lightGrayColor];
    _bitrateLabel.layer.masksToBounds = YES;
    _bitrateLabel.layer.cornerRadius  = 5;
    _bitrateLabel.font = [UIFont fontWithName:@"Helvetica-Bold" size:14];
    [_bitrateLabel setTextColor:[UIColor whiteColor]];
    _bitrateLabel.text = [NSString stringWithFormat: @"bitrate: %d", [[LiveVideoCoreSDK sharedinstance] bitrate]];
    [self.view addSubview:_bitrateLabel];
    
    /* 开始推流按钮 */
    float fstartButtonW = 80;
    float fstartButtonH = 40;
    float fstartButtonX = _screenWidth / 2.0 - fstartButtonW / 2.0;
    float fstartButtonY = _screenHeight / 2.0 - fstartButtonH / 2.0;
    _startButton = [[UIButton alloc] initWithFrame:CGRectMake(fstartButtonX, fstartButtonY, fstartButtonW, fstartButtonH)];
    _startButton.backgroundColor = [UIColor blueColor];
    _startButton.layer.masksToBounds = YES;
    _startButton.layer.cornerRadius  = 5;
    [_startButton setTitle:@"开始直播" forState:UIControlStateNormal];
    [_startButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    _startButton.titleLabel.font = [UIFont fontWithName:@"Helvetica-Bold" size:10];
    [_startButton addTarget:self action:@selector(onStartClicked:) forControlEvents:UIControlEventTouchDown];
    [self.view addSubview:_startButton];
}

- (void)onFlashBtnClicked:(UIButton *)button {
    if (_bCameraFrontFlag) {
        return;
    }
    
    _bTorchOnFlag = !_bTorchOnFlag;
    [[LiveVideoCoreSDK sharedinstance] setTorch:_bTorchOnFlag];
    if (_bTorchOnFlag) {
        [_flashButton setImage:[UIImage imageNamed:@"ic_camera_flash_open"] forState:UIControlStateNormal];
    } else {
        [_flashButton setImage:[UIImage imageNamed:@"ic_camera_flash_close"] forState:UIControlStateNormal];
    }
}

-(void) OnCameraChangeBtnClicked:(UIButton *)button{
    _bCameraFrontFlag = !_bCameraFrontFlag;
    [[LiveVideoCoreSDK sharedinstance] setUseFrontCamera:_bCameraFrontFlag];
}

- (void)OnFilterBtnClicked:(UIButton *)button {
    _bBeautyFilterOnFlag = !_bBeautyFilterOnFlag;
    [[LiveVideoCoreSDK sharedinstance] setBeautyFilter:_bBeautyFilterOnFlag];
    if (_bBeautyFilterOnFlag) {
        [_FilterButton setImage:[UIImage imageNamed:@"ic_live_beauty_open"] forState:UIControlStateNormal];
    } else {
        [_FilterButton setImage:[UIImage imageNamed:@"ic_live_beauty_close"] forState:UIControlStateNormal];
    }
}

-(void) OnExitBtnClicked:(UIButton *)button{
    NSLog(@"on exitclicked.Rtmp[%@] is ended", _rtmpUrl);
    [[LiveVideoCoreSDK sharedinstance] stop];
    [[LiveVideoCoreSDK sharedinstance] reset];
    
    /* destroy player */
    [self destroyPlayer];
    
    [[NSNotificationCenter defaultCenter] removeObserver: self];
    [self dismissViewControllerAnimated:YES completion:^{
        
    }];
}

- (void)onStartClicked:(id)sender {
    _uid = arc4random()%100000;
    if (_uid < 0) {
        _uid = -_uid;
    }
    
    _rtmpUrl = [NSString stringWithFormat:@"rtmp://test.ws.push.live.slw117.top/live/ios%d", _uid];
    /* use this url to play */
    _playUrl = [NSString stringWithFormat:@"rtmp://test.ws.pull.live.slw117.top/live/ios%d", _uid];
    
    _rtmpUrl = [NSString stringWithFormat:@"%@", _rtmpUrl];
    [[LiveVideoCoreSDK sharedinstance] startWithRtmpUrl:_rtmpUrl];
    
    [_startButton setHidden: YES];
}

-(void) startPreview{
    [[LiveVideoCoreSDK sharedinstance] initWithPreview: _cameraPreview];
    [LiveVideoCoreSDK sharedinstance].delegate = self;
    
    _bitrateLabel.text = [NSString stringWithFormat: @"bitrate: %d", [[LiveVideoCoreSDK sharedinstance] bitrate]];
    NSLog(@"Rtmp[%@] is connecting", _rtmpUrl);
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(bitrateDidChanged)
                                                 name:kLIVEVideoBitrateChangedNotification
                                               object:nil];
    
    [self UIInit];
    [self startPreview];
    _lastScale = 1;
    _bBeautyFilterOnFlag = YES;
    _bTorchOnFlag = NO;
    _bCameraFrontFlag = YES;
}

- (void)viewWillDisappear:(BOOL)animated {
    [[NSNotificationCenter defaultCenter] removeObserver:self
                                                    name:kLIVEVideoBitrateChangedNotification
                                                  object: nil];
    
    
    [super viewWillDisappear:animated];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)handlePinch:(UIPinchGestureRecognizer *)recognizer {
    NSLog(@"recognizer scale %f", recognizer.scale);
    
    _lastScale = recognizer.scale;
    
    /* prevent scale to be NAN */
    if (isnan(_lastScale)) {
        _lastScale = 1.0;
    }
    
    if (_lastScale < 1.0) {
        _lastScale = 1.0;
    }
    
    if (_lastScale > 6.0) {
        _lastScale = 6.0;
    }
    
    [[LiveVideoCoreSDK sharedinstance] setVideoZoomFactor:_lastScale];
}

- (void)handleTapGestureRecognizer:(UITapGestureRecognizer*)sender {
    CGPoint location = [sender locationInView: nil];
    NSLog(@"tap (%f,%f) (%f,%f)\n", location.x, location.y, _screenWidth, _screenHeight);
    
    CGFloat distX = 0.5 - (0.5 - location.x / _screenWidth) / _lastScale;
    CGFloat distY = 0.5 - (0.5 - location.y / _screenHeight) / _lastScale;
    
    NSLog(@"percent (%f,%f)\n", distX, distY);
    
    //判断是否是前摄像头，前摄像头的情况下对焦位置应取镜像位置
    //使用前摄像头
    if ([LiveVideoCoreSDK sharedinstance].useFrontCamera) {
        //对点进行旋转，在方法说明中，左上角的点为(0,0),实际测试(0,0)为右上角的点
        [[LiveVideoCoreSDK sharedinstance] setFocusPoint:CGPointMake(distY, distX)];
    }
    else {
        //对点进行旋转，在方法说明中，左上角的点为(0,0),实际测试(0,0)为右上角的点
        [[LiveVideoCoreSDK sharedinstance] setFocusPoint:CGPointMake(distY, 1 - distX)];
    }
}

#pragma UIGestureRecognizerDelegate
- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer {
    
    if ([gestureRecognizer isKindOfClass:UIPinchGestureRecognizer.class]) {
        _pinchGestureRecognizer.scale = _lastScale;
    }
    
    return YES;
}

//rtmp status delegate:
- (void) LiveConnectionStatusChanged: (LIVESessionState) sessionState{
    
    __weak __typeof(self) weakSelf = self;
    
    dispatch_async(dispatch_get_main_queue(), ^{
        switch (sessionState) {
            case kLIVESessionStatePreviewStarted:
                _RtmpStatusLabel.text = @"RTMP状态: 预览未连接";
                break;
            case kLIVESessionStateConnectFailed:
                _RtmpStatusLabel.text = @"连接失败";
                break;
            case kLIVESessionStateStarted:
                _RtmpStatusLabel.text =  [NSString stringWithFormat:@"RTMP状态: 已连接,url=%d", _uid];
                [self playerInit];
                break;
            case kLIVESessionStateDisconnect:
                _RtmpStatusLabel.text = @"RTMP状态: 中断连接";
                break;
            case kLIVESessionStateReconnected:
                _RtmpStatusLabel.text = @"RTMP状态: 重连成功";
                break;
            case kLIVESessionStatePoorNetwork:
                _RtmpStatusLabel.text = @"网络状态差";
                break;
            case kLIVESessionStateEnded:
                _RtmpStatusLabel.text = @"RTMP状态: 结束";
                break;
            default:
                break;
        }
        
    });
}

- (void)bitrateDidChanged {
    dispatch_async(dispatch_get_main_queue(), ^{
        _bitrateLabel.text = [NSString stringWithFormat: @"bitrate: %d", [[LiveVideoCoreSDK sharedinstance] bitrate]];
    });
}

- (void)destroyPlayer {
    [_player1 reset];
    [_player1 unSetupPlayer];
    _player1 = nil;
    
    [_player2 reset];
    [_player2 unSetupPlayer];
    _player2 = nil;
}

-(void)playerInit
{
//    _player1 init
    _player1 = [[FFMediaPlayer alloc] init];
    [_player1 setURL:_playUrl withDelegate: self];
    [_player1 prepareAsync];
    
    //_player2 init
    _player2 = [[FFMediaPlayer alloc] init];
    [_player2 setURL:@"rtmp://live.hkstv.hk.lxdns.com/live/hks" withDelegate: self];
//    [_player2 setURL:@"http://vm48002.baomihua.com/71d36a62e7eccf8bbee24beeb5ad0798/58CB54CB/pomoho_video/36831923_9_d6422832000d11e7b436008cfa1b8a78.mp4" withDelegate:self];
//    [_player2 prepareAsync];
}

/**
 * Called when the player prepared.
 *
 * @param player The shared media player instance.
 * @param arg Not use.
 */
- (void)mediaPlayer:(FFMediaPlayer *)player didPrepared:(id)arg {
    double fPlayViewW = [UIScreen mainScreen].bounds.size.width/2.0;
    double fPlayViewH = [UIScreen mainScreen].bounds.size.height/2.0;
    
    if (player == _player1) {
        _playerBackgroundView1 = [[UIView alloc] initWithFrame:CGRectMake(0, fPlayViewH - 50, fPlayViewW, fPlayViewH)];
        _playerBackgroundView1.backgroundColor = [UIColor blackColor];
        [self.view addSubview: _playerBackgroundView1];
        [_player1 setupPlayerWithContainerView: _playerBackgroundView1];
        [_player1 setVideoScalingMode:FFVideoScalingModeAspectFit animate:NO];
        [_player1 start];
    } else {
        _playerBackgroundView2 = [[UIView alloc] initWithFrame:CGRectMake(fPlayViewW, fPlayViewH + fPlayViewH / 2.0, fPlayViewW, fPlayViewW / 16.0 * 9.0)];
        _playerBackgroundView2.backgroundColor = [UIColor blackColor];
        [self.view addSubview: _playerBackgroundView2];
        [_player2 setupPlayerWithContainerView: _playerBackgroundView2];
        [_player2 start];
    }
}

/**
 * Called when the player playback completed.
 *
 * @param player The shared media player instance.
 * @param arg Not use.
 */
- (void)mediaPlayer:(FFMediaPlayer *)player playbackComplete:(id)arg {
    
}

/**
 * Called when the player have error occur.
 *
 * @param player The shared media player instance.
 * @param arg Contain the detail error information.
 */
- (void)mediaPlayer:(FFMediaPlayer *)player error:(id)arg {
    
}
@end
